﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Synchronization.Files;
using System.IO;

namespace Syncer
{
	public partial class Form1 : Form
	{
		#region fields
		private string _sourceDirectory;
		private string _destinationDirectory;
		#endregion

		protected Form1()
		{
			InitializeComponent();
		}

		public Form1(string sourceDirectory, string destinationDirectory)
			: this()
		{
			_sourceDirectory = sourceDirectory;
			_destinationDirectory = destinationDirectory;
		}

		#region privates

		private void op_ProgressUpdate(object sender, ProgressUpdateEventArgs e)
		{
			if (this.InvokeRequired)
			{
				this.Invoke(new EventHandler<ProgressUpdateEventArgs>(op_ProgressUpdate), new object[] { sender, e });
			}
			else
			{
				_lblTotal.Text = string.Format("Total: {0:00}", e.TotalPercentageComplete);
				_lblCurrent.Text = e.CurrentOperation;
				_pbTotal.Value = ((int)decimal.Floor(e.TotalPercentageComplete)) % 100;
				_pbCurrent.Value = ((int)decimal.Floor(e.CurrentOperationProgress)) % 100;


				Console.WriteLine(string.Format("{0:00} - {1} - {2:00}",
				e.TotalPercentageComplete, e.CurrentOperation, e.CurrentOperationProgress));
			}
		}

		private void _btnSync_Click(object sender, EventArgs e)
		{
			try
			{
				// Set options for the synchronization operation
				FileSyncOptions options = FileSyncOptions.ExplicitDetectChanges |
							FileSyncOptions.RecycleDeletedFiles | FileSyncOptions.RecyclePreviousFileOnUpdates | FileSyncOptions.RecycleConflictLoserFiles;

				DirectorySyncOperation op = new DirectorySyncOperation(
					new DirectoryInfo(_sourceDirectory), new DirectoryInfo(_destinationDirectory),
					null, options);

				_btnSync.Enabled = false;

				op.ProgressUpdate += new EventHandler<ProgressUpdateEventArgs>(op_ProgressUpdate);
				op.BeginAsyncOperation();
			}
			// yes lazy, but works for sample
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "Error");
			}
		}

		#endregion
	}
}